package com.example.service.other;


import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import com.example.common.Constants;


import com.example.common.Result;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.enums.RoleEnum;
import com.example.common.enums.RoleStatusEnum;
import com.example.exception.CustomException;
import com.example.mapper.medical.DepartmentMapper;
import com.example.mapper.medical.DoctorMapper;
import com.example.mapper.medical.HospitalMapper;
import com.example.mapper.medical.OfficeMapper;
import com.example.mapper.other.AdminMapper;
import com.example.mapper.shopping.BusinessMapper;
import com.example.mapper.shopping.MedicinesMapper;
import com.example.model.dto.AccountDto;
import com.example.model.entity.medical.Department;
import com.example.model.entity.medical.Doctor;
import com.example.model.entity.medical.Hospital;
import com.example.model.entity.medical.Office;
import com.example.model.entity.other.Account;
import com.example.model.entity.other.Admin;
import com.example.model.entity.shopping.Business;
import com.example.model.entity.shopping.Medicines;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 管理员表业务处理
 **/
@Service
public class AdminService {

    @Resource
    private AdminMapper adminMapper;
    @Resource
    private DepartmentMapper departmentMapper;
    @Resource
    private DoctorMapper doctorMapper;
    @Resource
    private OfficeMapper officeMapper;
    @Resource
    private HospitalMapper hospitalMapper;
    @Resource
    private BusinessMapper businessMapper;
    @Resource
    private MedicinesMapper medicinesMapper;

    /**
     * 新增
     */
    public void add(Admin admin) {
        Admin dbAdmin = adminMapper.selectByUsername(admin.getUsername());
        if (ObjectUtil.isNotNull(dbAdmin)) {
            throw new CustomException(ResultCodeEnum.USER_EXIST_ERROR);
        }
        if (ObjectUtil.isEmpty(admin.getPassword())) {
            admin.setPassword(Constants.USER_DEFAULT_PASSWORD);
        }
        if (ObjectUtil.isEmpty(admin.getName())) {
            admin.setName(admin.getUsername());
        }
        admin.setRole(RoleEnum.ADMIN.name());
        admin.setStatus(RoleStatusEnum.STATUS_OK.name());
        adminMapper.insert(admin);
    }
    /**
     * 删除
     */
    public void deleteById(Integer id) {
        adminMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            adminMapper.deleteById(id);
        }
    }

    /**
     * 修改
     */
    public void updateById(Admin admin) {
        adminMapper.updateById(admin);
    }

    /**
     * 根据ID查询
     */
    public Admin selectById(Integer id) {
        return adminMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<Admin> selectAll(Admin admin) {
        return adminMapper.selectAll(admin);
    }

    /**
     * 分页查询
     */
    public PageInfo<Admin> selectPage(Admin admin, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Admin> list = adminMapper.selectAll(admin);
        return PageInfo.of(list);
    }

    /**
     * 登录
     */
    public Account login(AccountDto accountDto) {
        Account dbAdmin = adminMapper.selectByUsername(accountDto.getUsername());
        if (ObjectUtil.isNull(dbAdmin)) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        if (!accountDto.getPassword().equals(dbAdmin.getPassword())) {
            throw new CustomException(ResultCodeEnum.USER_ACCOUNT_ERROR);
        }
        // 生成token
        String tokenData = dbAdmin.getId() + "-" + RoleEnum.ADMIN.name();
        String token = TokenUtils.createToken(tokenData, dbAdmin.getPassword());
        dbAdmin.setToken(token);
        return dbAdmin;
    }
    /**
     * 注册
     */
    public void register(Account account) {
        Admin admin = new Admin();
        BeanUtils.copyProperties(account, admin);
        add(admin);
    }

    /**
     * 修改密码
     */
    public void updatePassword(Account account) {
        Admin dbAdmin = adminMapper.selectByUsername(account.getUsername());
        if (ObjectUtil.isNull(dbAdmin)) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        if (!account.getPassword().equals(dbAdmin.getPassword())) {
            throw new CustomException(ResultCodeEnum.PARAM_PASSWORD_ERROR);
        }
        dbAdmin.setPassword(account.getNewPassword());
        adminMapper.updateById(dbAdmin);
    }


    public List<Map<String, Object>> selectPie() {
        List<Map<String, Object>> list = new ArrayList<>();
        // 1. 获取所有部门及其医生数量
        List<Department> departments = departmentMapper.selectAll(null);
        Map<Integer, Long> departmentDoctorCountMap = new HashMap<>();
        // 获取所有医生并统计每个部门的医生数量
        List<Doctor> doctors = doctorMapper.selectAll(null);
        for (Doctor doctor : doctors) {
            Integer officeId = doctor.getOfficeId();
            Office office = officeMapper.selectById(officeId);
            Integer departmentID = office.getDepartmentID();
            departmentDoctorCountMap.put(departmentID, departmentDoctorCountMap.getOrDefault(departmentID, 0L) + 1);
        }
        // 2. 计算每个部门的医生数量和总医生数量
        long totalDoctors = doctors.size();
        // 3. 构建每个部门的占比字典
        for (Department department : departments) {
            int departmentId = department.getId();
            long doctorCount = departmentDoctorCountMap.getOrDefault(departmentId, 0L);
            Map<String, Object> map = new HashMap<>();
            map.put("name", department.getDepartmentName());
            map.put("value", doctorCount);
            list.add(map);
        }
        return list;
    }

    public List<Map<String, Object>> selectHospitalBar() {
        List<Map<String, Object>> list = new ArrayList<>();
        // 获取当前用户信息，可能需要根据实际情况进行调整
        // 获取所有医院信息
        List<Hospital> hospitalsList = hospitalMapper.selectAll(null); // 假设有selectAll()方法获取所有医院
        // 统计每个医院的总挂号量
        Map<Integer, Integer> hospitalCounts = new HashMap<>();
        for (Hospital hospital : hospitalsList) {
            int hospitalId = hospital.getId();
            List<Doctor> doctors = doctorMapper.selectByHospitalId(hospitalId);
            int totalCount=0;
            if (!doctors.isEmpty()){
                 totalCount= doctorMapper.selectCountByHospitalId(hospitalId); //selectCountByHospitalId()方法获取挂号总量
            }
            hospitalCounts.put(hospitalId, totalCount);
        }
        // 按挂号总量降序排序并取前10
        List<Map.Entry<Integer, Integer>> topHospitals = hospitalCounts.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) // 按照挂号量降序排序
                .limit(10) // 取前10名
                .collect(Collectors.toList());
        // 构建返回的数据格式
        for (Map.Entry<Integer, Integer> entry : topHospitals) {
            Integer hospitalId = entry.getKey();
            Integer count = entry.getValue();
            // 获取医院名称
            Hospital hospital = hospitalMapper.selectById(hospitalId);//selectNameById()方法获取医院名称
            Map<String, Object> map = new HashMap<>();
            map.put("name", hospital.getName());
            map.put("value", count);
            list.add(map);
        }
        return list;
    }

    public List<Map<String, Object>> selectBusinessBar() {
        List<Map<String, Object>> list = new ArrayList<>();
        // 获取所有商家信息
        List<Business> businessesList = businessMapper.selectAll(null); // 假设有selectAll()方法获取所有商家
        // 统计每个商家的总销售额
        Map<Integer, Integer> businessSales = new HashMap<>();
        for (Business business : businessesList) {
            int businessId = business.getId();
            List<Medicines> medicines = medicinesMapper.selectByBusinessId(businessId);
            // 获取该商家的所有药品的总销量
            int totalSales=0;
            if (!medicines.isEmpty()){
                totalSales= medicinesMapper.selectTotalSalesByBusinessId(businessId); // selectTotalSalesByBusinessId()方法获取总销量
            }
            businessSales.put(businessId, totalSales);
        }
        // 按销售额降序排序并取前10
        List<Map.Entry<Integer, Integer>> topBusinesses = businessSales.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) // 按照销售额降序排序
                .limit(10) // 取前10名
                .collect(Collectors.toList());
        // 构建返回的数据格式
        for (Map.Entry<Integer, Integer> entry : topBusinesses) {
            Integer businessId = entry.getKey();
            Integer sales = entry.getValue();
            // 获取商家名称
            Business business = businessMapper.selectById(businessId); // 假设有selectById()方法获取商家信息
            Map<String, Object> map = new HashMap<>();
            map.put("name", business.getName());
            map.put("value", sales);
            list.add(map);
        }
        return list;
    }

}
